/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader;

import lombok.AccessLevel;
import lombok.Cleanup;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.Validate;
import org.jrose.api.annotation.common.ConfigurationLocation;
import org.jrose.core.util.AnnotationUtils;
import org.jrose.core.util.XMLUtils;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.InputStream;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Abstract configuration loader implementation.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-25 01:48
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
abstract public class AbstractConfigurationLoader<E extends Serializable> extends AbstractLoader implements InitializingLoader {
    private final AtomicBoolean initialized = new AtomicBoolean(false);

    @Override
    public synchronized void initializeLoader() {
        if (initialized.get()) {
            return;
        }

        ConfigurationLocation configurationLocation = AnnotationUtils.getAnnotation(getClass(), ConfigurationLocation.class);
        Validate.notNull(configurationLocation, "No @ConfigurationLocation found on '{}'", getClass().getName());

        Resource resource;
        switch (configurationLocation.type()) {
            case CLASSPATH: {
                resource = new ClassPathResource(configurationLocation.value());
                break;
            }
            case FILESYSTEM: {
                resource = new FileSystemResource(configurationLocation.value());
                break;
            }
            default: {
                throw new UnsupportedOperationException();
            }
        }
        Validate.isTrue(resource.exists(), "Configuration resource '%s' not exists", configurationLocation.value());

        try {
            @Cleanup InputStream inStream = resource.getInputStream();
            Document document = XMLUtils.getDocumentBuilder().parse(inStream);
            List<E> configurations = parseDocument(document.getDocumentElement());
            processConfigurations(configurations);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
        initialized.set(true);

        LoggerFactory.getLogger("config.loader").info("Loaded '{}'", configurationLocation.value());
    }

    abstract protected List<E> parseDocument(Element root);

    abstract protected void processConfigurations(List<E> configurations);
}
